const jsonwebtoken = require('jsonwebtoken')
// const db = [{name:"李雷"}];
const User = require('../models/users')
const Question = require('../models/questions')
const Answer = require('../models/answers')
const {secret} = require('../config');

class UsersCtl {
    async find(ctx){   //获取 get
        // ctx.body = await User.find();    //想要密码 .select('+password')
        const { per_page = 10 } = ctx.query
        const page = Math.max(ctx.query.page * 1 -1,1)  
        const perPage = Math.max(per_page * 1,1)
        ctx.body = await User
         .find({name: new RegExp(ctx.query.q)})
         .limit(perPage)
         .skip(page*perPage);
    }
    async findById(ctx){   //获取特定用户  get
        // 字段过滤
        const {fields=''} = ctx.query;
        const selectFields = fields.split(';').filter(f=>f).map(f => '+' + f).join('');
        const populateStr = fields.split(';').filter(f=>f).map(f => {
            if(f === 'employments'){
                return 'employments.job employments.company';
            }
            if(f === 'educations'){
                return 'educations.school educations.major';
            }
            return f;
        }).join(' ')
        const user = await User.findById(ctx.params.id).select(selectFields).populate(populateStr)
        if(!user){ctx.throw(412,'用户不存在')}
        ctx.body = user;
    }
    async create(ctx){   //创建 post新增
        ctx.verifyParams({
            name:{type:'string',required:true},
            password:{type:'string',required:true},
        });

        //保证唯一性的逻辑
        const { name } = ctx.request.body;
        const repeatedUser = await User.findOne({name});
        if(repeatedUser){ctx.throw(409,'用户已经占用')}

        const user = await new User(ctx.request.body).save();
        ctx.body = user;
    }
    //判断是不是自己
    async checkOwner(ctx,next){
        if(ctx.params.id !== ctx.state.user._id){ ctx.throw(403,'没有权限') }
        await next();
    }
    async update(ctx){   //更新 put修改
        ctx.verifyParams({
            name:{type:'string',required:false},
            password:{type:'string',required:false},
            avatar_url:{type:'string',require:false},
            gender:{type:'string',require:false},
            headline:{type:'string',require:false},
            locations:{type:'array',itemType:'string',require:false},
            business:{type:'string',require:false},
            employments:{type:'array',itemType:'object',require:false},
            educations:{type:'array',itemType:'object',require:false},
        })
        const user = await User.findByIdAndUpdate(ctx.params.id,ctx.request.body);
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user;
    }
    async delete(ctx){   //删除delete
        const user = await User.findByIdAndRemove(ctx.params.id)
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.status = 204;
    }
    async login(ctx){
        ctx.verifyParams({
            name:{type:'string',required:true},
            password:{type:'string',required:true},
    });
    // login jwt生成token 
    const user = await User.findOne(ctx.request.body)  //findOne这些是MongoDB的方法
    if(!user){ctx.throw(401,'用户名或密码不正确');}
    const {_id,name} = user
    const token = jsonwebtoken.sign({_id,name},secret,{expiresIn:'1d'}); 
    ctx.body = {token}
    }
    //获取自己关注的人   select()默认隐藏  populate() 具体的用户信息
    async listFollowing(ctx){
        const user = await User.findById(ctx.params.id).select('+following').populate('following')   
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user.following;
    }
    //粉丝
    async listFollowers(ctx){
        //获取用户 following限定条件
        const users = await User.find({ following: ctx.params.id });
        ctx.body = users;
    }
    //用户是否存在
    async checkUserExist(ctx,next){
        const user = await User.findById(ctx.params.id)
        if(!user){ ctx.throw(404,'用户不存在') }
        await next();
    }
    //关注
    async follow(ctx){
        //token  ctx.state.user._id
        const me = await User.findById(ctx.state.user._id).select('+following')
        if(!me.following.map(id => id.toString()).includes(ctx.params.id)){
            me.following.push(ctx.params.id);
            me.save();
        }
        ctx.status = 204;
    }
    //取消关注
    async unfollow(ctx){
        const me = await User.findById(ctx.state.user._id).select('+following')
        const index = me.following.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.following.splice(index,1);
            me.save();
        }
        ctx.status = 204;
    }


    //获取自己关注的话题   select()默认隐藏  populate() 具体的用户信息
    async listFollowingTopic(ctx){
        const user = await User.findById(ctx.params.id).select('+followingTopics').populate('followingTopics')   
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user.followingTopics;
    }
    //关注话题
    async followTopic(ctx){
        const me = await User.findById(ctx.state.user._id).select('+followingTopics')
        if(!me.followingTopics.map(id => id.toString()).includes(ctx.params.id)){
            me.followingTopics.push(ctx.params.id);
            me.save();
        }
        ctx.status = 204;
    }
    //取消关注话题
    async unfollowTopic(ctx){
        const me = await User.findById(ctx.state.user._id).select('+followingTopics')
        const index = me.followingTopics.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.followingTopics.splice(index,1);
            me.save();
        }
        ctx.status = 204;
    }
    async listQuestions(ctx){
        const questions = await Question.find({questions:ctx.params.id});
        ctx.body = questions;
    }


    //列出喜欢答案列表
    async listLikingAnswers(ctx){
        const user = await User.findById(ctx.params.id).select('+likingAnswers').populate('likingAnswers')   
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user.likingAnswers;
    }
    //点赞
    async likeAnswer(ctx,next){
        const me = await User.findById(ctx.state.user._id).select('+likingAnswers')
        if(!me.likingAnswers.map(id => id.toString()).includes(ctx.params.id)){
            me.likingAnswers.push(ctx.params.id);
            me.save();
            await Answer.findByIdAndUpdate(ctx.params.id, {$inc:{voteCount:1}})
        }
        ctx.status = 204;
        await next();
    }
    //取消点赞
    async unlikeAnswer(ctx){
        const me = await User.findById(ctx.state.user._id).select('+likingAnswers')
        const index = me.likingAnswers.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.likingAnswers.splice(index,1);
            me.save();
        }
        await Answer.findByIdAndUpdate(ctx.params.id, {$inc:{voteCount:-1}})
        ctx.status = 204;
    }


    //列出踩答案列表
    async listDisLikingAnswers(ctx){
        const user = await User.findById(ctx.params.id).select('+dislikingAnswers').populate('dislikingAnswers')   
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user.dislikingAnswers;
    }
    //踩
    async dislikeAnswer(ctx,next){
        const me = await User.findById(ctx.state.user._id).select('+dislikingAnswers')
        if(!me.dislikingAnswers.map(id => id.toString()).includes(ctx.params.id)){
            me.dislikingAnswers.push(ctx.params.id);
            me.save();
        }
        ctx.status = 204;
        await next();
    }
    //取消踩
    async undislikeAnswer(ctx){
        const me = await User.findById(ctx.state.user._id).select('+dislikingAnswers')
        const index = me.dislikingAnswers.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.dislikingAnswers.splice(index,1);
            me.save();
        }
        ctx.status = 204;
    }



    //列出收藏答案列表
    async listCollectingAnswers(ctx){
        const user = await User.findById(ctx.params.id).select('+collectingAnswers').populate('collectingAnswers')   
        if(!user){ctx.throw(404,'用户不存在');}
        ctx.body = user.collectingAnswers;
    }
    //收藏
    async CollectingAnswers(ctx,next){
        const me = await User.findById(ctx.state.user._id).select('+collectingAnswers')
        if(!me.collectingAnswers.map(id => id.toString()).includes(ctx.params.id)){
            me.collectingAnswers.push(ctx.params.id);
            me.save();
        }
        ctx.status = 204;
        await next();
    }
    //取消收藏
    async unCollectingAnswer(ctx){
        const me = await User.findById(ctx.state.user._id).select('+collectingAnswers')
        const index = me.collectingAnswers.map(id=>id.toString()).indexOf(ctx.params.id)
        if(index > -1){
            me.collectingAnswers.splice(index,1);
            me.save();
        }
        ctx.status = 204;
    }
}

module.exports = new UsersCtl();